package com.ebt.m.customer.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.customer.adapter.CustomerPolicyAdapter;
import com.ebt.m.customer.entity.PolicyBean;
import com.ebt.m.customer.event.EventCustomerFloatingButtonAction;
import com.ebt.m.customer.event.EventCustomerListRefreshOnly;
import com.ebt.m.customer.event.PolicyUpdateEvent;
import com.ebt.m.customer.fragment.BaseLazyFragment;
import com.ebt.m.customer.net.http.PolicyHttps;
import com.ebt.m.customer.net.json.ErrorJson;
import com.ebt.m.customer.net.json.PolicyAllJson;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.EBTProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 客户详情-保单列表
 * Created by archer.qi on 2016/12/12.
 */
public class FragmentCustomerPolicy extends BaseLazyFragment implements AdapterView.OnItemClickListener {
    public static final String ARG_CUSTOMER_ID = "CustomerID";
    @BindView(R.id.customer_active_policy_list)
    ListView customerActivePolicyList;
    @BindView(R.id.iv_empty)
    ImageView mEmptyImageView;
    @BindView(R.id.tv_empty)
    TextView mEmptyTextView;
    @BindView(R.id.btn_empty)
    Button mEmptyButton;
    @BindView(R.id.empty_container)
    LinearLayout mEmptyView;
    @BindView(R.id.load_refresh_net)
    TextView loadRefreshNet;
    @BindView(R.id.load_refresh)
    TextView loadRefresh;
    @BindView(R.id.progress)
    EBTProgress progress;
    Unbinder unbinder;
    private View noNetContainer;
    private View netSlowContainer;

    private CustomerPolicyAdapter mAdapter;
    private List<PolicyBean> listData = new ArrayList<>();

    private String customerId;
    private int currPolicyCount = 0;
    private int prevPolicyCount = 0;


    public static FragmentCustomerPolicy newInstance(String customerId) {
        FragmentCustomerPolicy frg = new FragmentCustomerPolicy();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_CUSTOMER_ID, customerId);
        frg.setArguments(bundle);
        return frg;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_active_policy, container, false);
        unbinder = ButterKnife.bind(this, contentView);
        setupViews(contentView);
        return contentView;
    }

    @Override
    public void onFirstUserVisible() {
        init();
    }

    private void setupViews(View view) {
        noNetContainer = view.findViewById(R.id.no_net_container);
        netSlowContainer = view.findViewById(R.id.net_slow_container);
        mEmptyButton.setVisibility(View.VISIBLE);
        mEmptyButton.setText("新建保单");
        customerActivePolicyList.setOnItemClickListener(this);
    }

    /**
     * 空图和错误图片显示逻辑
     *
     * @param empty
     * @param no_net
     * @param net_slow
     */
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
        if (empty) {
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyTextView.setText("暂无保单");
            mEmptyImageView.setImageResource(R.drawable.ic_empty_insurance);
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
        noNetContainer.setVisibility(no_net ? View.VISIBLE : View.GONE);
        netSlowContainer.setVisibility(net_slow ? View.VISIBLE : View.GONE);
    }


    private void init() {
        Bundle args = getArguments();
        if (args != null) {
            customerId = args.getString(ARG_CUSTOMER_ID);
        }
        EventBus.getDefault().register(this);
        showProgress();
        requestData(true);
    }

    private void showProgress() {
        if (progress != null) {
            progress.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgress() {
        if (progress != null) {
            progress.setVisibility(View.GONE);
        }
    }

    private void requestData(boolean fromInit) {
        PolicyHttps.getInstance(getActivity().getApplicationContext()).getAllCustomerPolicys(customerId, new PolicyHttps.onResponseCallback() {
            @Override
            public void onResponse(PolicyAllJson data) {
                hideProgress();
                listData = data.policyList;
                if (listData == null) {
                    currPolicyCount = 0;
                } else {
                    currPolicyCount = listData.size();
                }
                if (prevPolicyCount != currPolicyCount) {
                    if ((prevPolicyCount != 0 && currPolicyCount == 0)
                            || (prevPolicyCount == 0 && currPolicyCount != 0)) {
                        EventBus.getDefault().post(new EventCustomerListRefreshOnly());
                    }
                }
                prevPolicyCount = currPolicyCount;
                setAdapter();
            }

            @Override
            public void onError(ErrorJson error) {
                hideProgress();
                if (error != null) {
                    UIHelper.makeToast(getActivity(), error.message);
                }
                showEmpty(false, false, true);
            }

            @Override
            public void onFailure(Throwable t) {
                hideProgress();
                t.printStackTrace();
                showEmpty(false, true, false);
            }
        });
    }

    private void setAdapter() {
        showEmpty((listData == null || listData.size() == 0), false, false);
        if (mAdapter == null) {
            mAdapter = new CustomerPolicyAdapter(getActivity(), listData);
            customerActivePolicyList.setAdapter(mAdapter);
        }
        mAdapter.update(listData);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (mAdapter.isErp(i)) {
            goToPolicyDetail(mAdapter.getPolicyErpId(i));
        } else {
            // 非Erp用户，不能点击
        }
    }

    /*保单详情*/
    private void goToPolicyDetail(String policyErpId) {
        Bundle bundle = new Bundle();
        bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, "保单明细");
        bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4OLD_BASE);
        bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, false);
        bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, 5);

        bundle.putString(WebBaseActivity.WEB_TYPE_LINK, ConfigData.BASEURL_POLICY_DETAIL + "?id=" + policyErpId + "&from=native");
        goTo(PolicyDetailWebActivity.class, bundle);
    }

    private void goTo(Class<?> cls, Bundle data) {
        Intent intent = new Intent(getActivity(), cls);
        if (data != null) {
            intent.putExtras(data);
        }
        startActivity(intent);
    }

    @Subscribe
    public void onEvent(PolicyUpdateEvent ev) {
        switch (ev.option) {
            case 0: // Create
            case 1: // Update
            case 2: // Delete
                listData.clear();
                mAdapter = null;
                requestData(false);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_empty, R.id.load_refresh_net, R.id.load_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_empty:
                EventBus.getDefault().post(new EventCustomerFloatingButtonAction(EventCustomerFloatingButtonAction.Policy));
                break;
            case R.id.load_refresh_net:
                requestData(false);
                break;
            case R.id.load_refresh:
                requestData(false);
                break;
        }
    }
}
